package com.blog.wu.myblog.controller;

import com.blog.wu.myblog.base.BaseController;
import com.blog.wu.myblog.entity.ArticleInfo;
import com.blog.wu.myblog.entity.CategoryInfo;
import com.blog.wu.myblog.entity.UserInfo;
import com.blog.wu.myblog.service.ArticleInfoService;
import com.blog.wu.myblog.service.CategoryInfoService;
import com.blog.wu.myblog.util.PageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author wuyanshen
 * @Date 2018-09-25 下午2:14
 * @Discription 文章信息controller
 */
@Controller
@RequestMapping("/back/article")
public class ArticleInfoController extends BaseController {

    @Autowired
    private ArticleInfoService articleInfoService;

    @Autowired
    private CategoryInfoService categoryInfoService;

    /**
     * 条件查询文章信息
     *
     * @param articleInfo
     * @param model
     * @return java.lang.String
     * @Date 2018/10/25 3:55 PM
     * @Author wuyanshen
     */
    @RequestMapping(value = "get", method = RequestMethod.POST)
    public String find(ArticleInfo articleInfo, Model model) {
        List<ArticleInfo> list = articleInfoService.findList(articleInfo);
        model.addAttribute("artList", list);
        return "/back/article/article_list";
    }

    @RequestMapping("index")
    public String index(ArticleInfo articleInfo,Model model, @ModelAttribute("info") String info,Integer pageNo) {
        PageBean<ArticleInfo> pageBean = articleInfoService.findPage(articleInfo,pageNo);
        model.addAttribute("pageBean", pageBean);
        model.addAttribute("articleInfo", articleInfo);
        model.addAttribute("info", info);
        return "/back/article/article_list";
    }

    /**
     * @param articleInfo
     * @param model
     * @param session
     * @param attributes  用来拼接redirect跳转url跟的参数，跳转到的controller可以用@ModelAttribute接收参数
     * @return java.lang.String
     * @Date 2018/10/24 6:00 PM
     * @Author wuyanshen
     */
    @RequestMapping("add")
    public String add(ArticleInfo articleInfo, Model model, HttpSession session, RedirectAttributes attributes) {
        UserInfo userInfo = (UserInfo) session.getAttribute("userinfo");
        articleInfo.setArticleTime(new Date());
        if (userInfo != null) {
            articleInfo.setUserId(userInfo.getId());
        }
        boolean mark = articleInfoService.add(articleInfo);
        if (mark) {
            attributes.addAttribute("info", "添加文章成功");
        } else {
            attributes.addAttribute("info", "添加文章失败");
        }
        return "redirect:/back/article/index";
    }

    @RequestMapping("loadAdd")
    public String laodAdd(Model model) {
        List<CategoryInfo> cateList = categoryInfoService.findList(new CategoryInfo());
        model.addAttribute("cateList", cateList);
        return "/back/article/article_add";
    }

    @RequestMapping("loadUpdate")
    public String loadUpdate(ArticleInfo articleInfo, Model model) {
        ArticleInfo art = articleInfoService.get(articleInfo);
        List<CategoryInfo> cateList = categoryInfoService.findList(new CategoryInfo());
        model.addAttribute("cateList", cateList);
        model.addAttribute("art", art);
        return "/back/article/article_update";
    }


    @RequestMapping("update")
    public String update(ArticleInfo articleInfo, Model model) {
        List<CategoryInfo> cateList = categoryInfoService.findList(new CategoryInfo());
        model.addAttribute("cateList", cateList);
        articleInfo.setArticleTime(new Date());
        boolean mark = articleInfoService.update(articleInfo);
        model.addAttribute("art", articleInfo);
        if (mark) {
            model.addAttribute("info", "更新成功");
        } else {
            model.addAttribute("info", "更新失败");
        }
        return "/back/article/article_update";
    }

    @RequestMapping("delete")
    public String delete(ArticleInfo articleInfo, Model model) {
        boolean mark = articleInfoService.delete(articleInfo);
        if (mark) {
            model.addAttribute("info", "删除成功");
        } else {
            model.addAttribute("info", "删除失败");
        }
        return "redirect:/back/article/index";
    }


    /**
     * 上传图片
     *
     * @param upload
     * @return java.lang.String
     * @Date 2018/10/24 10:56 PM
     * @Author wuyanshen
     */
    @RequestMapping("upload")
    @ResponseBody
    public String upload(@RequestParam MultipartFile upload) {
        String url = articleInfoService.doPutFile(upload);

        return url;
    }

    /**
     * 上传图片
     *
     * @param upload
     * @return java.lang.String
     * @Date 2018/10/24 10:56 PM
     * @Author wuyanshen
     */
    @RequestMapping(value = "uploadFile", method = RequestMethod.POST)
    @ResponseBody
    public Map uploadFile(@RequestParam MultipartFile upload) {
        String url = articleInfoService.doPutFile(upload);
        String fileName = url.substring(url.lastIndexOf("/")).split("/")[1];
        logger.info("文件名：{}", fileName);
//            PrintWriter out = response.getWriter();
//            String callback = request.getParameter("CKEditorFuncNum");
//            response.setContentType("text/html;charset=UTF-8");
//            sb.append("<script type=\"text/javascript\">window.parent.CKEDITOR.tools.callFunction(" + callback + ",'" + url + "','')</script>");
//            return sb.toString();

        //上面的方式会报错"不正确的服务器响应" 根据官方文档https://ckeditor.com/docs/ckeditor4/latest/guide/dev_file_upload.html
        //需要返回json格式数据，格式如下
//            {
//                "uploaded": 1,
//                    "fileName": "foo.jpg",
//                    "url": "/files/foo.jpg"
//            }
        Map<String, Object> map = new HashMap<>();
        map.put("uploaded", "1");
        map.put("fileName", fileName);
        map.put("url", url);
        return map;

    }


}
